package com.sven.media;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatImageButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.sven.media.utils.NumUtil;
import com.sven.media.utils.RecordUtil;
import com.sven.media.utils.SdCardUtil;
import com.sven.media.utils.TimeUtil;
import com.sven.media.widget.WaveLineView;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by Sven on 2016/10/13 0013.
 */

public class VoiceRecorder extends Fragment {

    WaveLineView waveLineView;
    AppCompatImageButton btnRecord;
    TextView tvHint;
    TextView tvTime;

    private static final int MAX_TIME = 60;// 最长录音时间
    private static final int MIN_TIME = 1;// 最短录音时间
    private static final int RECORD_NO = 10; // 不在录音
    private static final int RECORD_ING = 11; // 正在录音
    private static final int RECORD_ED = 12; // 完成录音
    private int mRecordState = 0; // 录音的状态
    private double mRecordVolume;// 麦克风获取的音量值
    private String PATH;// 录音存储路径
    private String mRecordPath = "";// PATH
    private String typeAmr = ".caf";// 后缀名
    private float mRecordTime;// 录音的时间
    private OnRecordSuccessListener mOnRecordSuccessListener;
    private RecordUtil mRecordUtil;// 录音工具类
    MediaRecorder recorder;
    private Thread mRecordThread;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.view_recorder, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        tvHint = (TextView) view.findViewById(R.id.tv_hint);
        tvTime = (TextView) view.findViewById(R.id.tv_record_time);
        btnRecord = (AppCompatImageButton) view.findViewById(R.id.btn_record);
        waveLineView = (WaveLineView) view.findViewById(R.id.waveline);
        PATH = SdCardUtil.getSDPath() + "/ReleaseTheTask/Record/";

        btnRecord.setOnTouchListener(new View.OnTouchListener() {
                                         // 向上划动的距离
                                         int yLeng = -50;

                                         @Override
                                         public boolean onTouch(View v, MotionEvent event) {
                                             switch (event.getAction()) {
                                                 case MotionEvent.ACTION_DOWN:
                                                     try {
                                                         v.setPressed(true);
                                                         mRecordState = RECORD_ING;
                                                         mRecordPath = PATH + UUID.randomUUID().toString() + typeAmr;
                                                         mRecordUtil = new RecordUtil(mRecordPath);
                                                         try {
                                                             // 开始录音
                                                             mRecordUtil.start();
                                                         } catch (IOException e) {
                                                             e.printStackTrace();
                                                         }
                                                         // 初始化录音时间
                                                         // 大于最大录音时间则停止录音
                                                         // 每隔200毫秒就获取声音音量并更新界面显示
                                                         mRecordThread = new Thread(() -> {
                                                             // 初始化录音时间
                                                             mRecordTime = 0;
                                                             while (mRecordState == RECORD_ING) {
                                                                 // 大于最大录音时间则停止录音
                                                                 if (mRecordTime >= MAX_TIME) {
                                                                     mHandler.sendEmptyMessage(RECORD_NO);
                                                                 } else {
                                                                     try {
                                                                         // 每隔200毫秒就获取声音音量并更新界面显示
                                                                         Thread.sleep(100);
                                                                         mRecordTime += 0.1;
                                                                         if (mRecordState == RECORD_ING) {
                                                                             mRecordVolume = mRecordUtil
                                                                                     .getAmplitude();
                                                                             Log.e("Act_Que_Add", "mRecordVolume:" + mRecordVolume);
                                                                             mHandler.sendEmptyMessage(RECORD_ING);
                                                                         }
                                                                     } catch (InterruptedException e) {
                                                                         e.printStackTrace();
                                                                     }
                                                                 }
                                                             }
                                                         });
                                                         mRecordThread.start();
                                                     } catch (Exception ignored) {
                                                     }
                                                     return true;
                                                 case MotionEvent.ACTION_MOVE: {
                                                     if (event.getY() < yLeng) {
                                                         tvHint.setText(getContext().getString(R.string.up_cancle_record));
                                                         tvHint.setTextColor(Color.RED);
                                                     } else {
                                                         tvHint.setText(getContext().getString(R.string.up_cancle_record));
                                                         tvHint.setTextColor(Color.GRAY);
                                                     }
                                                     return true;
                                                 }

                                                 case MotionEvent.ACTION_UP:
                                                     v.setPressed(false);
                                                     if (mRecordState == RECORD_ING) {
                                                         // 停止动画效果
                                                         // stopRecordLightAnimation();
                                                         mRecordState = RECORD_ED;
                                                         try {
                                                             mRecordUtil.stop();
                                                         } catch (IOException e) {
                                                             e.printStackTrace();
                                                         }
                                                         mRecordVolume = 0;
                                                         // 如果录音时间小于最短时间
                                                         if (mRecordTime <= MIN_TIME) {
                                                             Toast.makeText(getContext(), getContext().getString(R.string.record_too_short), Toast.LENGTH_SHORT).show();
                                                             mRecordState = RECORD_NO;
                                                             mRecordTime = 0;
                                                             File file = new File(mRecordPath);
                                                             file.delete();
                                                         }
                                                         // 若上滑到距离，放弃录音
                                                         else if (event.getY() < yLeng) {
                                                             Toast.makeText(getContext(), getContext().getString(R.string.cancle_record), Toast.LENGTH_SHORT).show();
                                                             mRecordState = RECORD_NO;
                                                             mRecordTime = 0;
                                                             tvTime.setText(TimeUtil.toTimeStr(NumUtil.float2Int(mRecordTime)));
                                                             tvHint.setTextColor(Color.GRAY);
                                                             File file = new File(mRecordPath);
                                                             file.delete();
                                                         }
                                                         // 录音成功，获取音频路径mRecordPath和时长mRecordTime
                                                         else {
                                                             if (mOnRecordSuccessListener != null) {
                                                                 mOnRecordSuccessListener.OnRecordSucceed(mRecordPath, (long) mRecordTime);
                                                             }
                                                         }
                                                     }
                                                     return true;
                                                 default:
                                                     return false;
                                             }
                                         }
                                     }
        );
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 不在录音
                case RECORD_NO:

                    if (mRecordState == RECORD_ING) {
                        mRecordState = RECORD_ED;
                        try {
                            mRecordUtil.stop();
                            mRecordVolume = 0;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (mOnRecordSuccessListener != null) {
                        mOnRecordSuccessListener.OnRecordSucceed(mRecordPath, (long) mRecordTime);
                    }

                    if (mRecordThread != null && mRecordThread.isAlive()) {
                        mRecordThread.interrupt();
                    }

                    break;
                // 正在录音
                case RECORD_ING:
                    tvTime.setText(TimeUtil.toTimeStr(NumUtil.float2Int(mRecordTime)));
                    waveLineView.updateAmplitude((float) mRecordVolume * 0.1f / 3000);
                    break;
            }
        }
    };

    public void setOnRecordSuccessListenter(OnRecordSuccessListener listener) {
        this.mOnRecordSuccessListener = listener;
    }

    public interface OnRecordSuccessListener {
        void OnRecordSucceed(String path, long duration);
    }
}
